package abc.database.interfaces;

import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public interface DB2Helper extends ISqlHelper<Map<String, Object>> {
    default List<Map<String, Object>> getTableList(String dbname, JdbcTemplate jdbcTemplate) {
        String sql = "select name as table_name, '' as table_comment, 'table' as type from sysibm.systables where type = 'T'";
        return jdbcTemplate.queryForList(sql);
    }

    default List<Map<String, Object>> getColumnList(String dbname, JdbcTemplate jdbcTemplate) {
        List<Map<String, Object>> columns = new ArrayList<>();
        List<Map<String, Object>> tableList = this.getTableList(dbname, jdbcTemplate);
        if(tableList == null) {
            return columns;
        }
        tableList.forEach(a-> {
            if(!a.containsKey("table_name") || a.get("table_name")==null) {
                return;
            }
            String tablename = a.get("table_name").toString();
            String sql = String.format( "SELECT '%s' table, a.name annotationColumnName, a.name propertyName, a.name name, a.coltype dataType ,COALESCE(a.remarks, '') comment, 0 as isAutoIncrement, 1 convert, 0 versionField, 0 keyFlag, 0 keyIdentityFlag FROM sysibm.syscolumns a INNER JOIN sysibm.systables d on a.tbname=d.name LEFT JOIN sysibm.sysindexes n on n.tbname=d.name and SUBSTR(colnames,2)=a.name where d.type='T'and d.tbspace='%s'", tablename, tablename);
            List<Map<String, Object>> cols = jdbcTemplate.queryForList(sql);
            if(cols!=null && cols.size()>0) {
                columns.addAll(cols);
            }
        });

        return columns;
    }
}
